﻿using Microsoft.Extensions.Configuration;
using SqlSugar;

namespace Scm.Orm.Helper
{
    public class SqlSugarHelper
    {
        private static IConfiguration? _config;
        private static SqlSugarScope? _db;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="configuration"></param>
        public SqlSugarHelper(IConfiguration configuration)
        {
            _config = configuration;
            var DbCongif = _config.GetSection("DBConfig");
            _db = new(
                new ConnectionConfig()
                {
                    ConnectionString = DbCongif["ConnectionString"],//连接符字串
                    DbType = ChooseDbType(DbCongif["DBType"]),//数据库类型
                    IsAutoCloseConnection = true //不设成true要手动close
                },
                db =>
                {
                    db.Aop.OnLogExecuted = (sql, pars) =>
                    {
                        Console.WriteLine(sql);
                    };
                }
            );
        }


        /// <summary>
        /// 获取DB对象
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static SqlSugarScope GetDB()
        {
            return _db?? throw new Exception("数据库异常，请检查");
        }

        /**
         * 插入方法，主键使用雪花ID
         */
        public static long InsertForSnowflakeId(object record)
        {
            var db = SqlSugarHelper.GetDB();
            var Id = db.Insertable(record).ExecuteCommand();
            return Id;
        }

        /**
         * 创建雪花ID 
         */
        public static string GeneratorSnowId()
        {
            return SnowFlakeSingle.instance.getID().ToString();
        }

        /**
         * 创建雪花ID 
         */
        public static long GeneratorSnowIdLong()
        {
            return SnowFlakeSingle.instance.getID();
        }

        private static DbType ChooseDbType(string type)
        {
            return type switch
            {
                "MySql" => DbType.MySql,
                "SqlServer" => DbType.SqlServer,
                "Oracle" => DbType.Oracle,
                _ => DbType.MySql
            };
        }
    }
}
